import React, { Component } from 'react';
import './style.less'

const UE = window.UE;
export default class Editor extends Component {
    constructor(props) {
        super(props)
        this.state = {
            ueEditor: null,//富文本实例
            editorID: 'noticeContentID',//UE  id
        }
    }
    componentDidMount() {
        setTimeout(() => {
            this.initEditor()
        }, 100);
    }
    componentDidUpdate() {

    }
    componentWillUnmount() {

        // 组件卸载后，清除放入库的id
        if (typeof (UE.getEditor(this.state.editorID)) != 'undefined') {
            UE.getEditor(this.state.editorID).setHide()

            UE.getEditor(this.state.editorID).destroy();
        }
    }

    initEditor() {
        /*初始化编辑器*/
        const { editorID } = this.state
        const { mode } = this.props
        const ueEditor = UE.getEditor(editorID, {
            // 编辑器不自动被内容撑高
            autoHeightEnabled: true,
            // 初始容器高度
            initialFrameHeight: 300,
            // 初始容器宽度
            initialFrameWidth: 1100,
            catchRemoteImageEnable: false,
            placeholder: '请输入',
            topOffset: 100,
            autoFloatEnabled: false,
        });
        const _this = this;
        ueEditor.addListener('contentChange', (e) => {
            console.log(_this.formRefs, ' _this.formRefs');
            _this.props.contentChange(_this.getEditorContent())

        });


        ueEditor.commands['hqm'] = {
            execCommand: function (cmdName) {
                const input = document.createElement('input')
                input.type = 'file'
                input.click()
                input.onchange = (e) => {
                    const file = e.target.files[0]
                    console.log(_this.checkFileSize(file, 3));
                    if (_this.checkFileSize(file, 3)) {
                        let formData = new FormData();
                        formData.append("file", file);
                        fetch(React.$BaseUrl + '/admin/oss/image/upload',
                            {
                                method: "post",
                                headers: {
                                    RSnetToken: sessionStorage.getItem('RSnetToken')
                                },
                                body: formData,
                            })
                            .then((res) => {
                                res.json().then(result => {
                                    if (result.code === 0) {
                                        const { code, data, codeMessage
                                        } = result
                                        if (code === 0) {
                                            let { editor } = _this.state;
                                            editor.execCommand('insertHtml', `<img src="${data}"/>`);
                                        }
                                    }
                                })
                            })
                    }

                }
            }
        };
        ueEditor.ready((uEditor) => {
            if (!uEditor) {

                UE.delEditor(editorID);
                _this.initEditor();
            } else {
                if (mode === 'view') {
                    UE.getEditor(this.state.editorID).setDisabled()
                }
            }
        });
        this.setState({
            editor: ueEditor
        })


    }
    checkFileSize = (file, maxSize) => {
        console.log(file);

        const accept = ['image/jpg', 'image/png', 'image/jpeg']
        const fileType = 'image'
        if (fileType && !['image'].includes(fileType)) {
            React.$message({
                type: 'warning',
                content: `fileType字段类型错误,仅支持image类型`
            })
            return false
        }

        if (!accept.filter(item => item.indexOf(fileType) !== -1).includes(file.type)) {
            let mess = []
            accept.filter(item => {
                if (item.indexOf(fileType) !== -1) {
                    mess.push(item = item.replace(new RegExp(`${fileType}/`, 'g'), '.'))
                }
            })
            React.$message({
                type: 'warning',
                content: `${file.name} 不是 ${mess} 类型文件`
            })
            return false
        }
        if (file.size / 1024 / 1024 <= (maxSize || 3)) {
            return true
        } else {
            React.$message({
                type: 'info',
                content: `文件最大不能超过${(maxSize || 3)}M`
            })
            return false
        }
    };

    setEditorContent(con) {
        let { editor } = this.state;
        editor.ready((uEditor) => {
            if (uEditor) {
                con = con.replace(/video-js\" src/gi, "\" _url")
                con = con.replace(/<video/gi, "<img src='/manage/ueditor/themes/default/images/spacer.gif' style='background:url(/manage/ueditor/themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'")
                con = con.replace(/<\/video>/gi, "</img>")
                editor.setContent(con);
                clearTimeout(this.timer)
            }
        });
        this.timer = setTimeout(function () {
            editor.setContent(con);
        }, 700)
    }
    getEditorContent() {
        if (this.props.mode == 'view') return false
        let { editor } = this.state;
        let content = editor.getContent();

        return content;
    }
    render() {
        const { editorID } = this.state
        const { content } = this.props
        return (
            <textarea id={editorID}
                style={{ width: 0, height: 0 }}
                defaultValue={content}
                placeholder='请输入'
                onChange={this.getEditorContent} />
        );
    }
}
